"use strict";
const { Model } = require("sequelize");
const bcrypt = require("bcryptjs");
const { IdGenerator } = require("../utils/idGenerator");
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      // 每个用户有很多课程 关联 命名为复数
      models.User.hasMany(models.Course, {
        as: "courses",
      });

      models.User.belongsToMany(models.Course, {
        through: models.Like,
        foreignKey: "userId",
        as: "likeCourses",
      });
      // 关联用户表
      models.User.belongsTo(models.Dept, {
        foreignKey: "parentId",
        as: "dept",
      });
    }
  }

  User.init(
    {
      id: {
        type: DataTypes.INTEGER.UNSIGNED, // 无符号整数类型
        allowNull: false,
        primaryKey: true,
        defaultValue: function () {
          return IdGenerator.getNextID(); // 使用封装的ID生成方法
        },
      },
      email: DataTypes.STRING,
      username: DataTypes.STRING,
      password: {
        type: DataTypes.STRING,
        set(value) {
          this.setDataValue("password", bcrypt.hashSync(value, 10));
        },
      },
      nickname: DataTypes.STRING,
      sex: DataTypes.TINYINT,
      avatar: {
        type: DataTypes.STRING, //头像地址
        get() {
          const avatar = this.getDataValue("avatar");
          if (avatar) {
            return `${process.env.SERVER_REQUEST_ADDRESS}/${avatar}`;
          } else {
            return "";
          }
        },
      },
      parentId: DataTypes.INTEGER, //部门ID
      remark: DataTypes.STRING,
      rolesId: DataTypes.STRING, //权限ID
      roles: DataTypes.STRING, //权限名
      phone: DataTypes.STRING, //电话
      status: DataTypes.INTEGER, //启用状态
      createdAt: {
        allowNull: false,
        type: DataTypes.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: DataTypes.DATE,
      },
    },
    {
      sequelize,
      modelName: "User",
    },
  );
  return User;
};
